/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet;

import DataAccess.IDocAccess;
import Entity.IDoc;
import com.google.appengine.api.datastore.Text;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author phuc
 */
public class IDocServlet extends HttpServlet {
   IDocAccess access;
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            access = new IDocAccess();
            String action = request.getParameter("action");
            out.println(action);
            if (action.equals("add"))
            {
                String button = "";
                button = request.getParameter("btnSave");
                // if button Save is clicked
                if (!button.equals(""))
                {
                    // Add new IDoc
                    String date_str = request.getParameter("txtReceiveDate");
                    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                    Date ReceiveDate = df.parse(date_str);

                    date_str = request.getParameter("txtPubDate");
                    Date PubDate = df.parse(date_str);

                    //Chuyen Date sang String
                    //String date = df.format(ReceiveDate);
                    //out.print(date);
                    IDoc idoc = new IDoc();
                    idoc.setPubNum(request.getParameter("txtPubNum"));
                    idoc.setPubDate(PubDate);
                    idoc.setSignByName(request.getParameter("txtSignByName"));
                    idoc.setReceiveNum(request.getParameter("txtReceiveNum"));
                    idoc.setReceiveDate(ReceiveDate);
                    idoc.setClosed(Boolean.FALSE);
                    idoc.setSubject(request.getParameter("txtSubject"));
                    idoc.setNotes(request.getParameter("txtNotes"));
                    idoc.setBriefContent(request.getParameter("txtBriefContent"));
                    idoc.setODocID(request.getParameter("txtODocID"));
                    idoc.setAccountID(Long.parseLong(request.getParameter("txtAccountID").trim()));
                    idoc.setDocumentName(request.getParameter("fname"));
                    
                    if (access.addIDoc(idoc))
                        response.sendRedirect("/VanBanDen/DisplayIDoc.jsp");
                    else
                        out.print("Failed\n");
                }
                else
                {

                }

            }
            else if(action.equals("edit"))
            {
                out.print("Edit");
                String button = "";
                button = request.getParameter("btnSave");
                if (!button.equals(""))
                {
                    PersistenceManager pm = PMF.get().getPersistenceManager();
                    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                    Long ID;
                    ID = Long.parseLong(request.getParameter("txtID"));
                    IDoc idoc = pm.getObjectById(IDoc.class,ID);
                    idoc.setPubNum(request.getParameter("txtPubNum"));
                    idoc.setPubDate(df.parse(request.getParameter("txtPubDate")));
                    idoc.setReceiveDate(df.parse(request.getParameter("txtReceiveDate")));
                    idoc.setReceiveNum(request.getParameter("txtReceiveNum"));
                    idoc.setODocID(request.getParameter("txtODocID"));
                    idoc.setSubject(request.getParameter("txtSubject"));
                    idoc.setBriefContent(request.getParameter("txtBriefContent"));
                    idoc.setNotes(request.getParameter("txtNotes"));
                    if (request.getParameter("rdClosed").equals("true"))
                        idoc.setClosed(true);
                    else
                        idoc.setClosed(false);
                    response.sendRedirect("VanBanDen/DisplayIDoc.jsp");
                    pm.close();
                }
                
            }
            else if(action.equals("search"))
            {
                PersistenceManager pm = PMF.get().getPersistenceManager();
                String PubNum, Subject;
                Date FromDate, ToDate;
                SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                PubNum = request.getParameter("txtPubNum");
                Subject = request.getParameter("txtSubject");
                if (request.getParameter("txtFromDate") != "" && request.getParameter("txtToDate") != "")
                {
                    FromDate = df.parse(request.getParameter("txtFromDate"));
                    ToDate = df.parse(request.getParameter("txtToDate"));
                }
                else
                {
                    FromDate = null;
                    ToDate = null;
                }

                List<IDoc> results = access.searchIDoc(PubNum, Subject, FromDate, ToDate);
                HttpSession session = request.getSession(true);
                session.setAttribute("idoc", results);
                session.setAttribute("isSearch","y");
                response.sendRedirect("VanBanDen/DisplayIDoc.jsp");

                pm.close();
            }
        }
        catch(Exception e)
        {
            out.print(e);
        }
        finally {
            //out.print("Error");
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(IDocServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(IDocServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
